import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger('http');
  use(req: Request, res: Response, next: NextFunction) {
    const { method, originalUrl, query, body } = req;

    const startTime = Date.now();
    this.logger.log(`Incoming Request: ${method} ${originalUrl}`);
    if (method === 'GET' || method === 'get') {
      // this.logger.log(`get请求传参: ${JSON.stringify(params)}`); // 打印路由参数
      this.logger.log(`get请求传参: ${JSON.stringify(query)}`); // 打印查询参数
    }
    if (method === 'post' || method === 'POST') {
      this.logger.log(`post请求传参: ${JSON.stringify(body)}`); // 打印请求体
    }

    res.on('finish', () => {
      const { statusCode } = res;
      const processingTime = Date.now() - startTime;
      this.logger.log(
        `${method} ${originalUrl} ${statusCode}  - ${processingTime}ms`,
      );
    });

    next();
  }
}
